package com.yc.web.servlets;

import com.yc.bean.Admin;
import com.yc.web.model.JsonModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

@WebServlet("/admin.action")
public class AdminerServlet extends BaseServlet{

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        String aname = req.getParameter("aname");
        String apwd = req.getParameter("apwd");
        String captcha=req.getParameter("captcha");
        Admin admin=super.parseObjectFromRequest(req, Admin.class);
        HttpSession session = req.getSession();
        String sql="select * from admin where aname=? and apwd=? and status=0";
        List<Admin> list=db.select(Admin.class,sql,admin.getAname(),admin.getApwd());
        Map<String, Object> map=new HashMap<String,Object>();
        if (list!=null&&list.size()>0) {
            session.setAttribute("admin",list.get(0));
            //resp.getWriter().println("Login successful");
            map.put("code",0);
            map.put("data",list.get(0));
            map.put("msg","登录成功");
        } else {
           // resp.getWriter().println("Invalid aname or apwd");
            map.put("code",1);
            map.put("msg","登录失败");

        }
        super.writeObiectJson(map,resp);
    }
    public void findAllAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Admin c=super.parseObjectFromRequest(req,Admin.class);
        int page=1;
        if (req.getParameter("page")!=null){
            page=Integer.parseInt(req.getParameter("page"));
        }
        int limit=2;
        if (req.getParameter("limit")!=null){
            limit=Integer.parseInt(req.getParameter("limit"));
        }
        int skip=(page-1)*limit;
        //select*
        String sql="select * from admin where 1=1 ";
        String sql2="select count(*) as total from admin where 1=1 ";
        List<Object>params=new ArrayList<>();
        if (c.getAid()!=null){
            sql+=" and aid=? ";
            sql2+=" and aid=? ";
            params.add(c.getAid());
        }
        if (c.getAname()!=null && !"".equals(c.getAname())){
            sql+="and aname like '%"+c.getAname()+"%' ";
            sql2+="and aname like '%"+c.getAname()+"%' ";
            // params.add(c.getaname());
        }
//        if (c.g()!=null && !"".equals(c.getEmail())){
//            sql+="and aname like %"+c.getEmail()+"% ";
//            sql2+="and aname like %"+c.getEmail()+"% ";
//            //params.add(c.getEmail());
//        }
        if (c.getStatus()!=null){
            sql+="and status ="+c.getStatus();
            sql2+="and status ="+c.getStatus();
            //params.add(c.getEmail());
        }
        List<Admin>list=db.select(Admin.class,sql+"   order by aid limit "+limit+" offset "+skip,params.toArray());
        List<Map<String,Object>>result=db.select(sql2,params.toArray());
        int total=Integer.parseInt(result.get(0).get("total").toString());
        Map<String,Object>map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","查询用户成功");
        map.put("data",list);
        map.put("count",total);
        super.writeObiectJson(map,resp);

    }
    public void updateAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Admin c=super.parseObjectFromRequest(req,Admin.class);
        String sql = "UPDATE admin " +
                "SET aname = ?, " +
                "    limits = ?, " +
                "    status = ? " +
                "WHERE aid = ?;";
        if(c.getStatus()==null){
            c.setStatus(1);
        }
        if(c.getLimits()==null){
            c.setLimits(1);
        }
        int r=db.doUpdate(sql,c.getAname(),c.getLimits(),c.getStatus(),c.getAid());

        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0){
            map.put("code",0);
            map.put("msg","更新用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"更新用户失败");
            map.put("code",1);
            map.put("msg","更新用户失败");

        }
        super.writeObiectJson(map,resp);

    }
    public void allUsing(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String userid = req.getParameter("aid"); // 假设收到的是字符串 "1,2"
        String[] userIds = userid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE admin SET status = 0 WHERE aid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            HttpSession session=req.getSession();
            session.setAttribute("admin",r);
            map.put("code",0);
            map.put("msg","启用用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"启用用户失败");
            map.put("code",1);
            map.put("msg","启用用户失败");

        }
        super.writeObiectJson(map,resp);}
    public void allStop(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String userid = req.getParameter("aid"); // 假设收到的是字符串 "1,2"
        String[] userIds = userid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE admin SET status = 1 WHERE aid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            map.put("code",0);
            map.put("msg","停用用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"停用用户失败");
            map.put("code",1);
            map.put("msg","停用用户失败");

        }
        super.writeObiectJson(map,resp);}
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        String aname = req.getParameter("aname");
        String apwd=req.getParameter("apwd");
        String sql="insert into admin (aname, apwd) VALUES (?,?)";
        int result= db.doUpdate(sql,aname,apwd);
        JsonModel jm=new JsonModel();
        if (result>0){
            jm.setCode(1);
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }


    }


